<template>
  <div class="chart-wrapper" ref="wordChart"></div>
</template>

<script>
import echarts from "echarts";
require("echarts-wordcloud");
import { onMounted, onBeforeUnmount, ref, watch, routerChange } from "vue";
import { debounce } from "@/utils/index.js";
import useResize from "@/componentApi/useResize.js";
import { selectWordData } from "@/api/mockChart";
import yearData from "../js/2";

export default {
  name: "wordChart",
  setup() {
    let { abcode, year, parentInfo, routerChange } = useResize();
    let self = this;
    const wordChart = ref(null);
    let myChart = ref(null);

    const resizeHandler = debounce(() => {
      if (myChart) {
        myChart.resize();
      }
    }, 200);

    onMounted(() => {
      initEcharts();
      window.addEventListener("resize", resizeHandler);
    });
    onBeforeUnmount(() => {
      window.removeEventListener("resize", resizeHandler);
    });

    //模拟接口，获取echarts数据
    // const getWordData = async () => {
    //   const { data } = await selectWordData({
    //     abcode,
    //     year,
    //   });
    // initEcharts();
    // };

    // //渲染echarts图
    const initEcharts = () => {
      let updateFrequency = 2000;
      let dimension = 0;
      let countryColors = {
        业务一部: "#01E4FF",
        业务二部: "#0179FE",
        业务三部: "#FF7723",
        业务四部: "#B221E0",
        业务五部: "#00BAFF",
      };
      let datas = yearData;
      let years = [];
      for (let i = 0; i < datas.length; ++i) {
        if (years.length === 0 || years[years.length - 1] !== datas[i][4]) {
          years.push(datas[i][4]);
        }
      }
      function getFlag(countryName) {
        return countryName;
      }
      let startIndex = 5;
      let startYear = years[startIndex];

      myChart = echarts.init(wordChart.value);

      var option = {
        // tooltip: {
        //   trigger: "axis",
        //   axisPointer: {
        //     // 坐标轴指示器，坐标轴触发有效
        //     type: "shadow", // 默认为直线，可选为：'line' | 'shadow'
        //   },
        // },
        barWidth: 20,
        grid: {
          top: 25,
          bottom: 50,
          left: 70,
          right: 60,
        },
        xAxis: {
          name: "（万元）",
          default: "start",
          position: "top",
          max: "dataMax",
          // data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
          axisLabel: {
            formatter: function (n) {
              return Math.round(n) + "";
            },
          },
          axisLine: {
            show: true,
            //这是x轴文字颜色
            lineStyle: {
              color: "#8EE3FF",
              dashOffset: 10,
              opacity: 0.3,
              width: 1,
            },
          },
          splitLine: {
            show: true,
            lineStyle: {
              color: "#8EE3FF",
              opacity: 0.3,
            },
          },
          axisTick: {
            lineStyle: {
              color: "#8EE3FF",
              dashOffset: 10,
              opacity: 0.5,
              width: 1,
            },
          },
        },
        dataset: {
          source: datas.slice(1).filter(function (d) {
            //底部滑动数据
            return d[4] === startYear;
          }),
        },
        yAxis: {
          type: "category",
          inverse: true,
          max: 5, //数量
          axisLabel: {
            show: true,
            fontSize: 12,
            formatter: function (value) {
              return getFlag(value);
            },
            rich: {
              flag: {
                fontSize: 10,
                padding: 2,
              },
            },
          },
          axisLine: {
            //这是Y轴文字颜色
            show: false,
            lineStyle: {
              color: "#fff",
            },
          },
          axisTick: {
            //y轴刻度线
            show: false,
          },
          splitLine: {
            //网格线
            show: false,
          },
          animationDuration: 300,
          animationDurationUpdate: 300,
        },
        series: [
          {
            realtimeSort: true,
            seriesLayoutBy: "column",
            type: "bar",
            itemStyle: {
              color: function (param) {
                return countryColors[param.value[3]] || "#5470c6";
              },
            },
            encode: {
              x: dimension,
              y: 3,
            },
            label: {
              show: true,
              precision: 1,
              position: "right",
              valueAnimation: true,
              fontFamily: "monospace",
            },
          },
        ],
        // Disable init animation.
        animationDuration: 0,
        animationDurationUpdate: updateFrequency,
        animationEasing: "linear",
        animationEasingUpdate: "linear",
        graphic: {
          elements: [
            {
              type: "text",
              right: 160,
              bottom: 100,
              style: {
                text: startYear,
                font: "bolder 80px monospace",
                fill: "rgba(100, 100, 100, 0.5)",
              },
              z: 10,
            },
          ],
        },
      };
      myChart.setOption(option, true);
      for (let i = startIndex; i < years.length - 1; ++i) {
        (function (i) {
          setTimeout(function () {
            updateYear(years[i + 1]);
          }, (i - startIndex) * updateFrequency);
        })(i);
      }
      function updateYear(year) {
        let source = datas.slice(1).filter(function (d) {
          return d[4] === year;
        });
        option.series[0].data = source;
        option.graphic.elements[0].style.text = year;
        myChart.setOption(option, true);
      }
      // myChart.on("click", () => { //点击事件
      //   routerChange("/more");
      // });
    };

    watch();

    watch();

    return {
      wordChart,
    };
  },
};
</script>
